<?php

namespace App\Http\Controllers\Api\MiniToGame;

use App\Http\Controllers\Controller;
use App\Models\WxMinigameConfig;
use App\Services\MiniToGame\MiniToGameService;
use App\Services\WechatService;
use App\Services\WxMinigameLoginSessionService;
use Illuminate\Http\Request;

class StartController extends Controller
{
    public function index(Request $request)
    {
        $appid = $request->input('appid');
        $access_token = $request->input('access_token');
        $launch_info = $request->input('launch_info');

        $mini = WxMinigameConfig::where('appid', $appid)->first();
        if (!$mini) {
            return yqerr(6052);
        }

        $ret = WechatService::getInstance()->code2Session($appid, $mini->secret, $access_token);
        if (!$ret || (isset($ret['errcode']) && $ret['errcode'] !== 0)) {
            return yqerr(6026);
        }

        $openid      = $ret['openid'];
        $unionid     = $ret['unionid'] ?? '';
        $session_key = $ret['session_key'];
        $login = WxMinigameLoginSessionService::getInstance()->updateSessionKey($appid, $openid, $unionid, $session_key);

        $launch_info = json_decode($launch_info, true);
        $scene       = $launch_info['scene'];
        $querys      = $launch_info['query'];
        // 如果是从其他小游戏跳转过来，将信息整合到 query
        if (!empty($launch_info['referrerInfo'])) {
            $querys['referrer_appid'] = $launch_info['referrerInfo']['appId'] ?? '';
            $extra = $launch_info['referrerInfo']['extraData'] ?? [];
            if (!empty($extra)) {
                $querys = array_merge($querys, $extra);
            }
        }

        $jump_type = MiniToGameService::getInstance()->getJumpType($appid, $openid, $scene, $querys);
        $data = [
            'mtg_type' => $jump_type,
            'openid'   => $openid,
            'unionid'  => $unionid,
            'token'    => $login->token,
        ];

        return yqok($data);
    }
}
